import { getLocalStorage, setLocalStorage } from "../utils/fun.ts";
import { useConfig } from "./D8dConfigProvider.tsx";
import { useApiRequest } from "./useApiRequest.ts";
import { useQuery } from "@tanstack/react-query";
import type { UserData } from "../global.ts";
import { useNavigate } from "./useNavigate.ts";


/**
 * 检查用户登录状态
 * @returns 包含登录状态和加载状态的对象
 */
export const useCheckLogin = () => {
  const { token, tokenKey, apiUrl, setUserInfo, setUserMenu, setToken } =
    useConfig();
  const { request } = useApiRequest();
  const navigate = useNavigate();
  // 获取token
  const newtoken = token || getLocalStorage(tokenKey);

  // 使用 react-query 检查登录状态
  const { data: isLogin, isLoading } = useQuery({
    queryKey: ['checkLogin', newtoken],
    queryFn: async () => {
      if (!apiUrl.getUserInfo) {
        return false;
      }

      try {
        const result = await request({
          url: apiUrl.getUserInfo,
          method: "GET",
          headers: {
            Authorization: `Bearer ${newtoken}`,
          },
          data: {},
        });

        if (result?.code === 200 || result?.success) {
          const res = result.data;
          const user = res?.user as UserData;
          setUserInfo(user);
          setUserMenu(user?.roleInfo?.menuList);
          if (res?.token) {
            setLocalStorage(tokenKey, res?.token);
            setToken(res.token);
          }else {
            setToken(newtoken);
          }
          return true;
        } 
        else {
          console.log("登录检查错误:", result);
          setUserInfo(null);
          setUserMenu(null);
          setToken("");
          // navigate("/");
          return false;
        }
      } catch (error) {
        console.error("登录检查失败:", error);
        setUserInfo(null);
        setUserMenu(null);
        setToken("");
        navigate("/");
        return false;
      }
    },
    // 配置选项
    retry: 1, // 失败时最多重试1次
    staleTime: 5 * 60 * 1000, // 数据5分钟内认为是新鲜的
    gcTime: 10 * 60 * 1000, // 数据缓存10分钟
    refetchOnWindowFocus: true, // 窗口获得焦点时重新获取
    refetchOnReconnect: true, // 网络重连时重新获取
  });

  return {
    isLogin: isLogin ?? false,
    isLoading
  };
};
